<template>
  <view>
    <view class="b-head">
      <view
        class="b-head__xj"
        @tap="uploadGoods"
        :class="[imageList.length ? 'b-head__xj-offset' : '']"
      >
        <image src="../../static/img/xj.png"></image>
      </view>
      <text
        v-if="!imageList.length"
        style="color:#777"
      >添加商品图片
      </text>
      <swiper
        class="swiper"
        :indicator-dots="true"
        :autoplay="true"
        v-if="imageList.length"
      >
        <swiper-item
          v-for="(path,i) in imageList"
          :key="i"
        >
          <image :src="path"></image>
          <uni-icons
            class="icon"
            type="closeempty"
            size="28"
            color="#000"
            style="border-radius:50%;background:#ddd"
            @tap="deleteShowImg(i)"
          ></uni-icons>
        </swiper-item>
      </swiper>
    </view>
    <form @submit="formSubmit">
      <view class="b-set">
        <view class="b-set__item">
          <text>标题</text>
          <input
            type="text"
            placeholder="请填写商品标题"
            placeholder-style="font-size:14px;color:#999"
            name="title"
            v-model="title"
          >
        </view>
        <view class="b-set__item price">
          <text>价格</text>
          <view class="right">
            <input
              type="number"
              name="price"
              v-model="price"
            >
            <text style="color:#999">ARS$</text>
          </view>
        </view>
        <view class="b-set__item price">
          <text>商品库存</text>
          <view class="right">
            <input
              type="number"
              placeholder="请输入商品库存"
              placeholder-style="font-size:14px;color:#999"
              name="stock"
              v-model="stock"
            >
          </view>
        </view>
        <view class="b-set__item price">
          <text>运费</text>
          <view class="right">
            <input
              type="number"
              placeholder-style="font-size:14px;color:#999"
              name="freightCost"
              v-model="freightCost"
            >
            <text style="color:#999">ARS$</text>
          </view>
        </view>
      </view>
      <view class="b-textarea">
        <textarea
          class="b-textarea__t"
          placeholder="商品图文详细介绍..."
          placeholder-style="font-size:14px"
          maxlength="80"
          name="goodsDetail"
          v-model="goodsDetail"
        >

      </textarea>
        <robby-image-upload
          @add="addImage"
          @delete="deleteImage"
          limit="4"
          class="upload-img"
          :server-url="$base+'/seller/file/uploadPic'"
          :form-data="uploadFormData"
          v-model="imageData"
          :showUploadProgress='false'
          :header="header"
          fileKeyName="file"
        ></robby-image-upload>
      </view>
      <view class="b-state">
        <text>商品状态</text>
        <radio-group @change="radioChange1">
          <label
            class="uni-list-cell uni-list-cell-pd"
            v-for="(item, index) in items1"
            :key="item.value"
          >
            <view>
              <radio
                :value="item.value"
                :checked="index === current1"
              />
            </view>
            <view>{{item.name}}</view>
          </label>
        </radio-group>
      </view>
      <view class="b-recommend">
        <text>是否设为店家推荐</text>
        <radio-group @change="radioChange2">
          <label
            class="uni-list-cell uni-list-cell-pd"
            v-for="(item, index) in items2"
            :key="item.value"
          >
            <view>
              <radio
                :value="item.value"
                :checked="index === current2"
              />
            </view>
            <view>{{item.name}}</view>
          </label>
        </radio-group>
      </view>
      <view class="b-cabinet">
        <text>橱柜</text>
        <picker
          @change="cabinetChange"
          :value="cabinetIndex"
          :range="cabinet"
          :range-key="'windowName'"
        >
          <view
            style="color:#aaa"
            class="uni-input"
          >{{ cabinetName}}</view>
        </picker>
        <uni-icons
          class="icon"
          type="arrowdown"
          size="24"
          color="#bbb"
        ></uni-icons>
      </view>
      <view
        class="b-category"
        @tap="changeShow('QS_Picekr_custom2_2')"
      >
        <text>类目</text>
        <view>
          <text style="color:#aaa">{{categoryName}}</text>
          <uni-icons
            class="icon"
            type="arrowdown"
            size="24"
            color="#bbb"
          ></uni-icons>
        </view>

      </view>
      <QSpicker
        type="custom2"
        ref="QS_Picekr_custom2_2"
        pickerId="custom2_2"
        :dataSet="custom2Set_2"
        showReset
        @confirm="confirm($event)"
      />
      <view class="b-handle">
        <button
          class="b-handle__btn"
          formType="submit"
        >
          确定
        </button>
      </view>
    </form>
  </view>
</template>
<script>
import uniIcons from "@/components/uni-icons/uni-icons"
import robbyImageUpload from '@/components/robby-image-upload/robby-image-upload.vue'
let graceChecker = require("@/graceUI/jsTools/graceChecker.js");
import QSpicker from '@/components/QuShe-picker/QuShe-picker.vue';
export default {
  components: { uniIcons, robbyImageUpload, QSpicker },
  onLoad(opt) {
    this.getCabinet()
    this.getAllCategory()
    if (opt.detail) {
      this.redactFlag = true
      let data = JSON.parse(opt.detail)
      console.log(data)
      this.goodsId = data.goodsId
      this.title = data.title
      this.price = data.price
      this.stock = data.stock
      this.freightCost = data.freightCost
      this.categoryId = data.categoryId
      this.cabinetId = data.classifyId
      this.categoryName = data.categoryName
      this.cabinetName = data.classifyName
      this.goodsDetail = data.goodsDetail
      this.showGroupId = data.groupId //展示图片id
      this.current1 = data.state == 3 ? 1 : 0
      this.current2 = data.recommend ? 0 : 1
      console.log(this.current2)
      this.uploadFormData.groupId = data.detailGroupId // 商品详细图片id
      this.imageList = data.proRotaPic && data.proRotaPic.split(',').map(item => {   //展示图片
        return item = 'https://expay-mall.s3-sa-east-1.amazonaws.com' + item
      }) || []
      this.imageData = data.detailPics.map(item => {   //图文详细图片
        return item = 'https://expay-mall.s3-sa-east-1.amazonaws.com' + item
      })
      this.serveShowImgs = data.proRotaPic && data.proRotaPic.split(',') || [] // 服务端返回的展示图片路径
      this.serverDecImgs = data.detailPics  //服务端返回的图片详细路径
    }
  },
  data() {
    return {
      redactFlag: false,
      cabinetName: '请选择',
      categoryName: '请选择',
      categoryId: '', //类目ID
      cabinetId: '',//橱柜id
      header: { Authorization: uni.getStorageSync("sessionId") },
      index: 0,
      items1: [{ value: "2", name: "出售" }, { value: "3", name: "仓库" }],
      items2: [{ value: "true", name: "是" }, { value: "false", name: "否" }],
      cabinetIndex: 0,
      cabinet: [],
      imageData: [],
      imageList: [],
      current1: 0,
      current2: 0,
      price: '',
      title: '',
      goodsDetail: '',
      stock: '',
      freightCost: '',
      defaultSrc: '',
      serveShowImgs: [],
      serverDecImgs: [],
      deleteShowImgs: [],
      uploadFormData: {
        ruleGroupId: '45d63e5aab174b01a71bda96405a8451',
        groupId: ''
      },
      showGroupId: '',
      custom2Set_2: {
        itemObject: {
          step_1: [{
            name: "江西"
          }, {
            name: "山东"
          }],
          step_2: [

          ]
        },
        steps: {
          step_1_value: "categoryName", //第一级显示的属性名
          step_2_value: "categoryName", //第二级显示的属性名
          step_3_value: "" //第三级显示的属性名
        },
        defaultValue: [0, 0], //初始数据
        linkageNum: 2, //3 表示为3级联动
        linkage: true //true 表示开启联动
      }
    }
  },
  methods: {
    changeShow(name) {
      this.$refs[name].show();
    },
    confirm(res) {
      console.log(res);
      this.categoryName = res.data.steps2.categoryName
      this.categoryId = res.data.steps2.categoryId
    },
    async getCabinet() {
      let res = await this.$http.POST({
        url: '/seller/window/listWindows'
      })
      if (res.code == 200) {
        this.cabinet = res.data
      }
    },
    async getAllCategory() {
      let res = await this.$http.GET({
        url: '/seller/goods/getAllCategory',
      })
      if (res.code == 200) {
        // console.log(res.data)
        this.custom2Set_2.itemObject.step_1 = res.data
        for (let item of res.data) {
          this.custom2Set_2.itemObject.step_2.push(item.childrens)
        }
      }
    },
    uploadGoods() {
      uni.chooseImage({
        count: 6, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: res => {
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            let blobShowImg = res.tempFilePaths[i]
            this.$ld('上传中')
            uni.uploadFile({
              url: `${this.$base}/seller/file/uploadPic`, //仅为示例，非真实的接口地址
              filePath: res.tempFilePaths[i],
              name: 'file',
              header: { Authorization: uni.getStorageSync('sessionId') },
              formData: {
                ruleGroupId: '48194162f64449f5baf0c629fb98cfc1',
                groupId: this.showGroupId
              },
              success: (uploadFileRes) => {

                uni.hideLoading()
                let res = JSON.parse(uploadFileRes.data)
                if (res.code == 200) {
                  this.showGroupId = res.data.groupId
                  let serveImg = res.data.filePath
                  this.serveShowImgs.push(serveImg)
                  this.imageList.push(blobShowImg)
                } else {
                  return uni.showToast({ title: res.msg, icon: 'none' })
                }
              }
            });
          }
        }
      });
    },
    async deleteShowImg(i) {   //删除展示图片
      // console.log(this.deleteShowImgs)
      this.$ld("删除中")
      let res = await this.$http.POST({
        url: '/seller/file/deleteGoodsPics',
        data: {
          filePath: this.serveShowImgs[i],
          groupId: this.showGroupId
        }
      })
      uni.hideLoading()
      if (res.code == 200) {
        this.deleteShowImgs.push(this.serveShowImgs[i])
        this.imageList.splice(i, 1)
        this.serveShowImgs.splice(i, 1)
      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    },
    async deleteImage(e) {  //删除图文详细图片
      let filePath = this.serverDecImgs.splice(e.index, 1)
      this.$http.POST({
        url: '/seller/file/deleteGoodsPics',
        data: {
          filePath,
          groupId: this.uploadFormData.groupId
        }
      })

    },
    bindPickerChange: function (e) {
      this.index = e.target.value
    },
    cabinetChange(e) {
      // console.log(e)
      this.cabinetIndex = e.target.value
      this.cabinetName = this.cabinet[this.cabinetIndex].windowName
      this.cabinetId = this.cabinet[this.cabinetIndex].windowId
    },
    async deleteServeShowImg() {
      this.$ld()
      let res = await this.$http.POST({
        url: '/seller/file/deleteGoodsPics',
        data: {
          filePath: this.deleteShowImgs,
          groupId: this.showGroupId
        }
      })
      uni.hideLoading()
      console.log(res)
      if (res.code == 200) {

      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }

    },
    addImage(e) {
      console.log(e)
      this.uploadFormData.groupId = e.serverData.groupId
      this.serverDecImgs.push(e.serverData.filePath)
      console.log(this.serverDecImgs)
    },
    radioChange1: function (evt) {  //商品状态
      console.log()
      for (let i = 0; i < this.items1.length; i++) {
        if (this.items1[i].value === evt.target.value) {
          this.current1 = i;
          break;
        }
      }
    },
    radioChange2: function (evt) {
      for (let i = 0; i < this.items2.length; i++) {
        if (this.items2[i].value === evt.target.value) {
          this.current2 = i;
          break;
        }
      }
    },
    async formSubmit(e) {
      let reg = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;
      if (reg.test(this.title) || reg.test(this.goodsDetail) ) {
        return uni.showToast({ title: '请勿输入特殊字符或者表情', icon: 'none' })
      }

      var rule = [
        { name: "title", checkType: "notnull", checkRule: "1,10", errorMsg: "标题不能为空" },
        { name: "price", checkType: "notnull", checkRule: "1,5", errorMsg: "请输入价格" },
        { name: "stock", checkType: "notnull", errorMsg: "请输入商品库存" },
        { name: "freightCost", checkType: "notnull", errorMsg: "请输入运费" },
        { name: "goodsDetail", checkType: "notnull", checkRule: "", errorMsg: "请输入商品描述" }
      ];
      let formData = e.detail.value;
      var checkRes = graceChecker.check(formData, rule);
      if (checkRes) {
        const shopId = uni.getStorageSync('shopInfo').shopId
        let url = this.redactFlag ? '/seller/goods/modify' : '/seller/goods'
        let res = await this.$http.POST({
          url,
          data: {
            classifyId: this.cabinetId, //橱柜id
            categoryId: this.categoryId, //类目id
            proRotaPic: this.serveShowImgs,
            groupId: this.serveShowImgs.length ? this.showGroupId : '', //展示图id
            detailGroupId: this.uploadFormData.groupId,
            price: this.price,
            shopId,
            stock: this.stock,
            title: this.title,
            state: this.items1[this.current1].value,
            recommend: this.items2[this.current2].value,
            goodsDetail: this.goodsDetail,
            goodsId: this.goodsId || '',
            filePaths: this.deleteShowImgs,
            freightCost: this.freightCost
          }
        })
        if (res.code == 200) {
          uni.showToast({ title: this.redactFlag ? '修改成功' : '发布成功' });
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/GoodsManage/goodsList'
            });
          }, 1000);
        } else {
          uni.showToast({ title: res.msg, icon: "none" });
        }
      } else {
        uni.showToast({ title: graceChecker.error, icon: "none" });
      }
    }
  },
}
</script>

<style lang="scss" scoped>
@import '@/scss';
@include b(head) {
  @include size(100%, 450upx);
  @include flex-cl;
  position: relative;
  .swiper {
    width: 100%;
    height: 100%;
    image {
      @include size(100%, 100%);
    }
    .icon {
      position: absolute;
      right: 12upx;
      top: 12upx;
    }
  }
  @include e(xj) {
    @include size(120upx, 120upx);
    background: #4d91f9;
    border-radius: 50%;
    margin-bottom: 10upx;
    @include flex-center;
    image {
      @include size(64upx, 55upx);
    }
  }
  @include e(xj-offset) {
    position: absolute;
    right: 24upx;
    bottom: 24upx;
    z-index: 100;
  }
}
@include b(set) {
  background: #fff;
  padding: 0 30upx;
  @include e(item) {
    height: 90upx;
    border-bottom: 1px solid #eee;
    @include flex-bw;
    input {
      text-align: right;
    }
    &.type {
      position: relative;
      .icon {
        position: absolute;
        right: 10upx;
        top: 32%;
      }
    }
    picker {
      flex: 1;
      text-align: right;
      padding-right: 60upx;
      z-index: 111;
    }
    &.price {
      input {
        height: 56upx;
      }
      .right {
        display: flex;
        align-items: center;
        text {
          padding-left: 10upx;
        }
      }
    }
  }
}
@include b(textarea) {
  background: #fff;
  position: relative;
  .upload-img {
    position: absolute;
    bottom: 0;
  }
  @include e(title) {
    height: 92upx;
    line-height: 92upx;
    border-bottom: 1px solid #eee;
  }
  @include e(t) {
    width: 100%;
    padding: 10upx 0 0 30upx;
    box-sizing: border-box;
    height: 380upx;
  }
}
@include b(state) {
  @include flex-bw;
  background: #fff;
  padding: 0 30upx;
  height: 120upx;
  border-bottom: 1px solid #eee;
  radio-group {
    display: flex;
  }
  .uni-list-cell {
    display: flex;
    margin-left: 40upx;
  }
}
@include b(recommend) {
  @include flex-bw;
  background: #fff;
  padding: 0 30upx;
  height: 120upx;
  radio-group {
    display: flex;
  }
  .uni-list-cell {
    display: flex;
    margin-left: 40upx;
  }
}
@include b(cabinet) {
  position: relative;
  background: #fff;
  height: 90upx;
  padding: 0 30upx;
  margin-top: 20upx;
  @include flex-bw;
  picker {
    flex: 1;
    text-align: right;
    padding-right: 54upx;
    z-index: 111;
  }
  .icon {
    position: absolute;
    right: 34upx;
    top: 32%;
  }
}
@include b(category) {
  background: #fff;
  height: 90upx;
  @include flex-bw;
  padding: 0 30upx;
  margin-top: 20upx;
}
@include b(handle) {
  @include flex-center;
  margin: 30upx 0;
  @include e(btn) {
    @include size(320upx, 80upx);
    line-height: 80upx;
    background: #0099ff;
    color: #fff;
    @include flex-center;
    border-radius: 14upx;
  }
}
</style>